package com.eairlv.utils.utils;

import com.alibaba.fastjson.JSON;
import com.eairlv.utils.validator.user.UserInformation;
import com.eairlv.utils.validator.user.UserValidator;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class HttpUtil {

    public static String getUserInfoFromHeader(NativeWebRequest webRequest) {
        String str = webRequest.getHeader(UserValidator.USER_INFORMATION);
        return parseUserInfoStr(str);
    }

    public static String getUserInfoFromHeader(HttpServletRequest request) {
        String str = request.getHeader(UserValidator.USER_INFORMATION);
        return parseUserInfoStr(str);
    }

    private static String parseUserInfoStr(String str) {
        if (null == str || str.length() == 0) {
            return null;
        }
        String rs = null;
        try {
            rs = URLDecoder.decode(str, "UTF-8");
        } catch (Exception e) {
            rs = str;
        }
        if (JSON.isValid(rs)) {
            return rs;
        }
        return null;
    }

    public static String writeUserInfoToHeaderString(UserInformation userInfo) {
        try {
            return URLEncoder.encode(JSON.toJSONString(userInfo), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
